#pragma once

class TreeViewItem
{
	friend class TreeView;
	std::set<TreeViewItem*> m_subItems;
	bool m_isExpanded;
	bool m_isHighlighted;

	static Texture* m_pPlusTexture;
	static Texture* m_pMinusTexture;
	static CFont* m_font;

	Vertex2F m_position;

	TreeViewItem* m_pParent;
	TreeView* m_pTreeView;

	std::string m_szText;

	void _CalculateVertices(Vertex3FRHWT* pInput, ui32& index);
	void _Draw(ui32& maxDraw, ui32& curDraw, ui32& scroll);
	void _OnClick() { m_isExpanded = !m_isExpanded; }
	ui32 _GetNumItems();
	bool _CheckSubItems(Vertex2F& pos, ui32& index, ui32& scroll);
	void _DrawHighlight(ui32 x, ui32 y, ui32 len);
	void _UnhighlightExcept(TreeViewItem* pItem);

public:
	TreeViewItem();
	TreeViewItem(std::string szName);
	TreeViewItem(TreeViewItem* pParent);
	TreeViewItem(TreeViewItem* pParent, std::string szName);

	TreeViewItem* GetParent() { return m_pParent; }
	
	void SetParent(TreeViewItem* pParent);
	void SetPosition(Vertex2F position);
	void SetText(std::string szNewText) { m_szText = szNewText; }
	void AddSubItem(TreeViewItem* pItem);
	std::string GetText() { return m_szText; }
	TreeViewItem* AddSubItem(std::string szText);
};

class TreeView : public UIElement
{
	std::vector<TreeViewItem*> m_items;
	ui32 m_numDraw, m_curScroll;
	typedef void (*Callback)(void*, TreeViewItem*);
	typedef void (*ScrollCB)(void*, ui32);

	Callback m_callBack;
	void* m_pAsyncObject;

	ScrollCB m_scrollCB;

public:
	TreeView(ui32 x, ui32 y, ui32 w, ui32 h);
	void Draw();
	void SetCallback(Callback pFunction, void* pAsyncObject)
	{
		m_callBack = pFunction;
		m_pAsyncObject = pAsyncObject;
	}

	void ScrollSetCallback(ScrollCB pFunction, void* pAsyncObject)
	{
		m_scrollCB = pFunction;
		m_pAsyncObject = pAsyncObject;
	}

	void AddItem(TreeViewItem* pItem);
	void MouseActivity(bool left, Vertex2F pos, bool up);
	void ModPosition(float x, float y);
	void SetScroll(ui32 pos) { m_curScroll = pos; }
	ui32 GetNumItems();
	void _OnCallback(TreeViewItem* pItem)
	{
		if(m_callBack)
			m_callBack(m_pAsyncObject, pItem);
	}

	void UnhighlightExcept(TreeViewItem* pItem);

	void _OnExpand(ui32 index)
	{
		m_curScroll = index;
		if(m_scrollCB)
			m_scrollCB(m_pAsyncObject, index);
	}
};